package com.wrox.earthquake;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;

public class EarthquakeActivity extends Activity {
	private static final int SHOW_PREFERENCES = 1;
	public static final String PREF_MIN_MAG = "PREF_MIN_MAG";
	public static final String PREF_UPDATE_FREQ = "PREF_UPDATE_FREQ";
	public static final String PREF_AUTO_UPDATE = "PREF_AUTO_UPDATE";
	
	private int minimumMagnitude = 3;
	private int updateFrequency = 60;
	private boolean autoUpdate = true;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_earthquake);
        updateFromPreferences();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_earthquake, menu);
        return true;
    }

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case R.id.menu_settings:
			Intent i = new Intent(this, FragmentPreferences.class);
			this.startActivityForResult(i, SHOW_PREFERENCES);
			return true;
		}
		return false;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if (requestCode == SHOW_PREFERENCES) 
			updateFromPreferences();
		final EarthquakeListFragment earthquakeListFragment = 
				(EarthquakeListFragment) getFragmentManager().findFragmentById(R.id.fragment_earthquake_list);
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				earthquakeListFragment.refreshEarthquakes();
			}			
		});
		t.start();
	}

	private void updateFromPreferences() {
		Context context = getApplicationContext(); 
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
		minimumMagnitude = Integer.parseInt(prefs.getString(PREF_MIN_MAG, "3"));
		updateFrequency = Integer.parseInt(prefs.getString(PREF_UPDATE_FREQ, "60"));
		autoUpdate = prefs.getBoolean(PREF_AUTO_UPDATE, true);
	}

	public int getMinimumMagnitude() {
		return minimumMagnitude;
	}	
	
	
}
